package com.atguigu.java8.stream;

import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

public class ForkJoinCaculate extends RecursiveTask<Long> {

    private final long start;

    private final long end;

    public ForkJoinCaculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    private static final long THRESHOLD = 10000;

    @Override
    protected Long compute() {
        long length = end - start;

        if (length <= THRESHOLD) {
            return LongStream.rangeClosed(start, end).sum();
        } else {
            long middle = (start + end) / 2;
            ForkJoinCaculate left = new ForkJoinCaculate(start, middle);
            left.fork();
            ForkJoinCaculate right = new ForkJoinCaculate(middle + 1, end);
            right.fork();

            return left.join() + right.join();
        }
    }
}
